<?php
/**
 ***********************************************************************************************************************
 * 访问记录处理类
 * @author llq
 ***********************************************************************************************************************
 */
namespace soa\access\model;

/**
 * Class danger
 * @package soa\access\model
 */
class danger
{
    /**
     * IP
     */
    const KEY_PREFIX = 'access:danger:';

    /**
     *
     */
    const AUTO_BLOCK_KEY = 'access:auto:block';
    /**
     * @var array
     */
    private $fields = [
        'daily',
        'hourly',
        'minutely',
        'update_at',
        'useragent',
        'service',
        'client_id'
    ];


    /**
     * @param $ip
     * @param array $dict
     * @return int
     */
    public function add($ip, array $dict)
    {
        //echo 'aa';
        //myprint($dict);
        foreach($dict as $key => $val) {
            if(!in_array($key, $this->fields)) {
                unset($dict[$key]);
            }
        }

        $ret = $this->getRedisService()->hset(self::KEY_PREFIX . $dict['service'], $ip, json_encode($dict));
        // 次日零点过期 仅仅记录一天数据 减少redis内存占用
        $expireat = strtotime('+1 day', strtotime(date('Y-m-d')));
        $this->getRedisService()->expireat(self::KEY_PREFIX, $expireat);
        return $ret;
    }

    /**
     * @return array
     */
    public function get($service)
    {
        if(empty($data = $this->getRedisService()->hGetAll(self::KEY_PREFIX . $service))) {
            return [];
        }

        foreach($data as $ip => $val) {
            $data[$ip] = json_decode($val, true);
        }

        return $data;
    }


    /**
     * @param $ip
     * @return bool
     */
    public function del($service, $ip)
    {
        if(empty($ip) || !is_string($ip)) {
            return false;
        }
        return $this->getRedisService()->hDel(self::KEY_PREFIX . $service, $ip);
    }

    /**
     * @param $ip
     * @return bool|int|mixed
     */
    public function pushAutoBlockQueue($ip)
    {
        return $this->getRedisService()->push(self::AUTO_BLOCK_KEY, $ip);
    }

    /**
     * @var \artisan\cache\cacheDriver
     */
    private $redisService;

    /**
     * @return \artisan\cache\cacheDriver
     */
    private function getRedisService()
    {
        if(empty($this->redisService)) {
            $this->redisService = \artisan\cache::connect('firewall');
        }
        return $this->redisService;
    }

}